﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSVSTS.Common;
using MSVSTS.DataAccess;
using MSVSTS.Encryption;
using BookOnline.Business;
using BookForm.cls;
using System.IO;
namespace BookForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            treeType_Create("");
        }


        private void InitTreeType()
        {
            treeType.Nodes.Clear();
            treeType.CheckBoxes = false;
            treeType.ShowPlusMinus = true;
            treeType.AfterSelect += new TreeViewEventHandler(treeType_AfterSelect);
        }
        private void treeType_Create(string SelectText)
        {
            InitTreeType();

            Book_TypeSys sys = new Book_TypeSys();
            DataSet ds = new DataSet();

            Book_ContentsSys sys_ = new Book_ContentsSys();
            DataSet ds_ = new DataSet();

            try
            {
                ds = sys.GetBook_TypeDs();
                ds_ = sys_.GetBook_ContentsDs();

                treeType.BeginUpdate();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //ReplaceQueue.Enqueue(node["id"].InnerText + "|" + xmlNode["default"].InnerText + "|" + xmlNode["replace"].InnerText);
                    TreeNode treeNode = new TreeNode(dr["TypeName"].ToString() + "|" + dr["ID"].ToString());

                    foreach (DataRow dr_ in ds_.Tables[0].Rows)
                    {
                        if (dr_["BookType"].ToString() == dr["ID"].ToString())
                        {
                            CategoryCls type = new CategoryCls();
 
                            type.BookContentsID = dr_["ID"].ToString();
                            type.BookName = dr_["BookName"].ToString();
                            type.BookTypeID = dr_["BookType"].ToString();
                            type.BookCode = dr_["Code"].ToString();
                            //type.Url = dr_["Url"].ToString();


                            TreeNode treeNode_ = new TreeNode(type.BookName);
                            treeNode_.Tag = type;

                            //if (this.Title.Text.Trim().Length > 0 && SelectText.ToString().Trim().Length > 0)
                            //{
                            //    if (this.Title.Text.Trim().Equals(SelectText))
                            //    {
                            //        SelectNode = treeNode_;
                            //    }
                            //}
                            treeNode.Nodes.Add(treeNode_);
                        }
                    }

                    treeType.Nodes.Add(treeNode);
                }

                treeType.EndUpdate();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                ds.Dispose();
                ds_.Dispose();
                ds = null;
                ds_ = null;
                sys = null;
                sys_ = null;
            }


        }

        //类别树形结构 方法、初始化
        private void treeType_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (e.Node.Tag != null)
            {
                CategoryCls category = e.Node.Tag as CategoryCls;

                this.CodeStr.Text = category.BookCode.ToString();
                this.ContentID.Text = category.BookContentsID.ToString();

                try
                {
                    BindDictionary(this.comboBox1,category.BookContentsID);
                }
                catch (Exception ex)
                { }
                finally { 
                 
                }
            }
            else
            {
                //string bookNameID = treeType.SelectedNode.Text.Split('|')[1].ToString();
                //this.BookNameID.Text = bookNameID;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strHTML = this.textBox1.Text;
            string random = Random_Class.GenerateRandom(8, Random_Class.RandomType.NumberAndLowercased);
            string strPostData = String.Format("formhash={0}&referer=http%3A%2F%2Fwww.52mtg.com%2Fbbs%2Findex.php&loginfield=username&username={1}&password={2}&questionid=0&answer=&cookietime=2592000&loginmode=&styleid=&loginsubmit=%CC%E1%BD%BB"
                , random
                , "starcake"
                , "fighters"
                );
            strHTML = WEBFunc.GetSyncHTML(WEBFunc.CreateWebRequest(strHTML, string.Empty, strPostData, System.Text.Encoding.GetEncoding("gb2312")), System.Text.Encoding.GetEncoding("gb2312"));

            string strTitle = RegexCls.GetMatch(strHTML, "<span id=\"lbChapterName\" class=\"bkt\">(.*)</span>");
            this.title.Text = strTitle.ToString();
            string strBody = RegexCls.GetMatch(strHTML, "<script src='(.*).txt'>");
            
           // strBody = RegexCls.GetMatch(strBody, "<script src='(.*)'></script>");
            strBody=DownloadOneFileByURL(strBody + ".txt");
          //  Utils.ResponseFile(strBody+".txt","d","txt");
            strBody = Utils.ClearSpace(strBody);
            strBody = Utils.ClearBR(strBody);
            this.body.Text = strBody.Replace("document.write('", "").Replace("');", "").Replace("<p><ahref=http://www.cmfu.com>起点中文网www.cmfu.com欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！</a>","");
            // <span id="lbChapterName" class="bkt">第一章 群魔乱舞</span>
            // <div id="content" align="left"><script src='http://files.qidian.com/Author4/96587/2567930.txt'></script></div>


        }

        public static string DownloadOneFileByURL(string url)
        {

            return WEBFunc.GetSyncHTML(WEBFunc.CreateWebRequest_(url, string.Empty, "", System.Text.Encoding.GetEncoding("gb2312")), System.Text.Encoding.GetEncoding("gb2312"));
 
        }

        public void BindDictionary(System.Windows.Forms.ComboBox dropDownList,string bookid)
        {
            Book_VolumeSys sys = new Book_VolumeSys();
            string where = " where BookID="+bookid;
            DataSet ds = sys.GetBook_VolumeDs(where);
            dropDownList.Items.Clear();
            //dropDownList.Items.Add(new ListItem("请选择...", "请选择..."));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //ListControl listItem = new ListControl (dr["ProvinceName"].ToString(), dr["ProvinceName"].ToString());
                ListItem item = new ListItem(dr["ID"].ToString(), dr["VolumeName"].ToString());

                dropDownList.Items.Add(item);
                //dropDownList.DisplayMember = dr["VolumeName"].ToString();
                //dropDownList.ValueMember = dr["ID"].ToString();

            }

            dropDownList.SelectedIndex = 0;
            ds.Dispose();
            ds = null;
            sys = null;
        }


        private void button2_Click(object sender, EventArgs e)
        {
            Book_ChapterData data = new Book_ChapterData();
            Book_ChapterSys sys = new Book_ChapterSys();
            try
            {
                data.ChapterName = this.title.Text;
                data.ChapterBody = this.body.Text;
                data.Code = this.CodeStr.Text;
                data.AddUser = "starcake";
                data.AddUserID = 1;
                data.BookID = int.Parse(this.ContentID.Text);
                data.VolumeID = int.Parse(((ListItem)this.comboBox1.SelectedItem).ID);
                sys.Book_ChapterData = data;
                if (sys.InsertData())
                {
                    this.label4.Text = this.title.Text + "--ok";
                    this.title.Text = "";
                    this.body.Text = "";
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally {
                data = null;
                sys = null;
            }
        }




    }
}
